const cloud = require('wx-server-sdk')

cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV,
})

exports.main = async () => {
	const wxContext = cloud.getWXContext()
	const { OPENID, UNIONID } = wxContext

	const collection = cloud.database().collection('gn_user')

	try {
		const checkIfLogin = await collection.where({ _id: OPENID }).get()
		// 如果用户已经存在
		if (checkIfLogin?.data?.length) {
			return {
				code: 0,
				data: checkIfLogin.data[0],
				msg: '登录成功',
			}
		}
		// 用户不存在，创建用户并添加到数据库
		const { _id } = await collection.add({
			data: {
				_id: OPENID,
				avatar:
					'https://636c-cloud1-0g1tg2fnddbcfb9a-1325753704.tcb.qcloud.la/gaga-notebook/avatar/_default.jpg?sign=5503997c6d1b80d046349b4e1d272250&t=1714646654',
				follower: [],
				nickname: '微信用户',
				unionid: UNIONID,
				space: [],
				collection: [],
				subscription: [],
				follow: [],
			},
		})
		const checkIfRegister = await collection.where({ _id }).get()
		// 如果用户已经存在
		if (checkIfRegister?.data?.length) {
			return {
				code: 0,
				data: checkIfRegister.data[0],
				msg: '注册成功',
			}
		}
		return {
			code: 1,
			data: null,
			msg: '获取信息失败',
		}
	} catch (err) {
		throw err
	}
}
